package net.lainiao.manager.control;

import net.lainiao.base.model.ShiroUser;
import net.lainiao.manager.shiro.SuperUser;
import net.lainiao.manager.viewModel.LoginUser;
import net.lainiao.service.service.ShiroUserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

/**
 * Created by Administrator on 2017/1/4.
 */
@Controller
public class HomeControl {
    @Resource
    private SuperUser superUser;
    @Resource
    private ShiroUserService shiroUserService;

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String index() {
        return "login";
    }

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login() {
        return "login";
    }

    @RequestMapping(value="/loginout",method =RequestMethod.GET)
    public String loginout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "/login";
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String loginAction(@ModelAttribute LoginUser loginUser, ModelMap modelMap) {
        if (superUser.isAdmin(loginUser.getUsername(), loginUser.getPassword())) {
            addToken(loginUser);
        } else {
            ShiroUser shiroUser = shiroUserService.login(loginUser.getUsername(), loginUser.getPassword());
            if (shiroUser != null) {
                addToken(loginUser);
            } else {
                modelMap.put("mess", "登录失败");
                return "/login";
            }
        }
        return "redirect:/main/index";
    }

    private void addToken(LoginUser loginUser){
        SecurityUtils.getSecurityManager().logout(SecurityUtils.getSubject());
        UsernamePasswordToken token = new UsernamePasswordToken(loginUser.getUsername(), loginUser.getPassword());
        if(!StringUtils.isBlank(loginUser.getRemeberme())){
            token.setRememberMe(true);
        }
        Subject subject = SecurityUtils.getSubject();
        subject.login(token);
    }

    @RequestMapping(value = "/unauthorized")
    public String unauthorized(HttpSession session) {
        return "unauthorized";
    }

}
